package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.User;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet(name = "index",value = "/index")
public class IndexServlet extends HttpServlet {

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取登录记录，看用户是否登录
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		// 根据session中的isLogin名字获取登录记录中对象信息
		User user = (User) session.getAttribute("isLogin");
		if (user == null) {
			// 没有用户信息，跳转登录
			String url = "/javaweblogin_war_exploded/login.html";
			out.println("当前没登录，请登录<a href = '" + url +  "'>登录页面</a>");
		} else {
			String logoutUrl = "/javaweblogin_war_exploded/LogoutServlet";
			out.println("欢迎：" + user.getUsername() + "登录     <a href='" + logoutUrl +"'>退出</a>");
			// 有用户信息，则将存有用信息的sessionId发给前端
			Cookie cookie = new Cookie("JSESSIONID", session.getId());
			response.addCookie(cookie);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
